<template>
  <div class="upload-wrap">
    <el-upload
      action="https://jsonplaceholder.typicode.com/posts/"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :class="{ disabled: isDisabled }"
      :file-list="fileList"
      :http-request="upload"
      :on-change="headleChange"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <!-- 进度条 -->
    <el-progress v-if="showProg" :percentage="percent" style="width:180px"></el-progress>
    <el-dialog title="预览图片" :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
// 导入
import COS from 'cos-js-sdk-v5'
// 实例化一个腾讯云的操作对象
let cos = new COS({
  SecretId: 'AKIDoVyHMDvRkqhJvMYWQBi3A2e2B9vTmrhI',
  SecretKey: 'PbbOxHPK2VjkX6QVN0OVMzRkrmRs9HH5'
})
export default {
  computed: {
    isDisabled () {
      return this.fileList.length > 0
    }
  },
  data () {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      // 用来保存图片的
      fileList: [],
      showProg:false,
      percent:0
    }
  },

  methods: {
    // 文件状态发生改变触发
    headleChange (file, fileList) {
      this.fileList = fileList
    },
    handleRemove (file, fileList) {
      // console.log(file, fileList)
      // 点击删除清空数组,上传就可以显示了
      this.fileList=[]
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
   
    upload (params) {
      // console.log('我是自定义',params);
      this.showProg=true
      cos.putObject(
        {
          Bucket: 'hr72-1306809259' /* 必须 名字*/,
          Region: 'ap-guangzhou' /* 存储桶所在地域，必须字段 */,
          Key: params.file.name /* 必须 */,
          StorageClass: 'STANDARD',
          Body: params.file, // 上传文件对象

          // 回调函数,上传进度的回调函数
          onProgress: (progressData)=> {
            // console.log(JSON.stringify(progressData))
            this.percent=progressData.percent*100
          }
        },
        (err, data) => {
          // console.log(err || data)
          // console.log(data);
          if (!err) {
            // console.log(data.Location);
            this.fileList = [{ url: 'http://' + data.Location }]
          }
          this.percent=0
          this.showProg=false
        }
      )
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-wrap {
  .disabled {
    ::v-deep .el-upload--picture-card {
      display: none;
    }
  }
}
</style>
